<?php
class dcAgendaPlugin
{
        private $blog;
        private $con;
        private $table;
        private $post_table;
        private $prefix;
        private $id;
        private $without_password;
        public function __construct(&$core)
        {
                $this->core =& $core;
                $this->blog =& $core->blog;
                $this->id = $core->blog->id;
                $this->prefix = $this->blog->prefix;
                $this->con =& $this->blog->con;
                $this->table = $this->blog->prefix.'agenda';
                $this->post_table = $this->blog->prefix.'post';
                $this->without_password = false;
        }


	
	/// @name Entries management methods
	//@{
	/**
	Retrieves entries. <b>$params</b> is an array taking the following
	optionnal parameters:
	
	- no_content: Don't retrieve entry content (excerpt and content)
	- post_type: Get only entries with given type (default "post", array for many types and '' for no type)
	- post_id: (integer) Get entry with given post_id
	- post_url: Get entry with given post_url field
	- user_id: (integer) Get entries belonging to given user ID
	- cat_id: (integer or array) Get entries belonging to given category ID
	- cat_id_not: (boolean) if true, cat_id parameter will be a "not" query
	- cat_url: (string or array) Get entries belonging to given category URL
	- cat_url_not: (boolean) if true, cat_url parameter will be a "not" query
	- post_status: (integer) Get entries with given post_status
	- post_selected: (boolean) Get select flaged entries
	- post_year: (integer) Get entries with given year
	- post_month: (integer) Get entries with given month
	- post_day: (integer) Get entries with given day
	- post_lang: Get entries with given language code
	- search: Get entries corresponding of the following search string
	- sql: Append SQL string at the end of the query
	- from: Append SQL string after "FROM" statement in query
	- order: Order of results (default "ORDER BY post_dt DES")
	- limit: Limit parameter
	
	@param	params		<b>array</b>		Parameters
	@param	count_only	<b>boolean</b>		Only counts results
	@return	<b>record</b>	A record with some more capabilities
	*/
	public function getPosts($params=array(),$count_only=false)
	{
		if ($count_only)
		{
			$strReq = 'SELECT count(P.post_id) ';
		}
		else
		{
			if (!empty($params['no_content'])) {
				$content_req = '';
			} else {
				$content_req =
				'post_excerpt, post_excerpt_xhtml, '.
				'post_content, post_content_xhtml, post_notes, ';
			}
			
			$strReq =
			'SELECT P.post_id, P.blog_id, P.user_id, P.cat_id, post_dt, '.
			'post_tz, post_creadt, post_upddt, post_format, post_password, '.
			'post_url, post_lang, post_title, '.$content_req.
			'post_type, post_meta, post_status, post_selected, post_position, '.
			'post_open_comment, post_open_tb, nb_comment, nb_trackback, '.
			'U.user_name, U.user_firstname, U.user_displayname, U.user_email, '.
			'U.user_url, '.
			'C.cat_title, C.cat_url, '.
			'G.date_debut, G.date_fin ';
		}
		
		$strReq .=
		'FROM '.$this->prefix.'post P '.
		'INNER JOIN '.$this->prefix.'user U ON U.user_id = P.user_id '.
		'LEFT OUTER JOIN '.$this->prefix.'category C ON P.cat_id = C.cat_id '.
		'LEFT OUTER JOIN '.$this->prefix.'agenda G ON G.post_id = P.post_id ';
		
		if (!empty($params['from'])) {
			$strReq .= $params['from'].' ';
		}
		
		$strReq .=
		"WHERE P.blog_id = '".$this->con->escape($this->id)."' ";
		
		if (!$this->core->auth->check('contentadmin',$this->id)) {
			$strReq .= 'AND ((post_status = 1 ';
			
			if ($this->without_password) {
				$strReq .= 'AND post_password IS NULL ';
			}
			$strReq .= ') ';
			
			if ($this->core->auth->userID()) {
				$strReq .= "OR P.user_id = '".$this->con->escape($this->core->auth->userID())."')";
			} else {
				$strReq .= ') ';
			}
		}
		
		#�Adding parameters
		if (isset($params['post_type']))
		{
			if (is_array($params['post_type']) && !empty($params['post_type'])) {
				$strReq .= 'AND post_type '.$this->con->in($params['post_type']);
			} elseif ($params['post_type'] != '') {
				$strReq .= "AND post_type = '".$this->con->escape($params['post_type'])."' ";
			}
		}
		else
		{
			$strReq .= "AND post_type = 'post' ";
		}
		
		if (!empty($params['post_id'])) {
			if (is_array($params['post_id'])) {
				array_walk($params['post_id'],create_function('&$v,$k','if($v!==null){$v=(integer)$v;}'));
			} else {
				$params['post_id'] = array((integer) $params['post_id']);
			}
			$strReq .= 'AND P.post_id '.$this->con->in($params['post_id']);
		}
		
		if (!empty($params['post_url'])) {
			$strReq .= "AND post_url = '".$this->con->escape($params['post_url'])."' ";
		}
		
		if (!empty($params['user_id'])) {
			$strReq .= "AND U.user_id = '".$this->con->escape($params['user_id'])."' ";
		}
		
		if (!empty($params['cat_id']))
		{
			if (is_array($params['cat_id'])) {
				array_walk($params['cat_id'],create_function('&$v,$k','if($v!==null){$v=(integer)$v;}'));
			} else {
				$params['cat_id'] = array((integer) $params['cat_id']);
			}
			
			if (empty($params['cat_id_not'])) {
				$strReq .= 'AND P.cat_id '.$this->con->in($params['cat_id']);
			} else {
				$strReq .= 'AND (P.cat_id IS NULL OR P.cat_id NOT '.$this->con->in($params['cat_id']).') ';
			}
		}
		
		if (!empty($params['cat_url']))
		{
			if (is_array($params['cat_url'])) {
				array_walk($params['cat_url'],create_function('&$v,$k','$v=(string)$v;'));
			} else {
				$params['cat_url'] = array((string) $params['cat_url']);
			}
			
			if (empty($params['cat_url_not'])) {
				$strReq .= 'AND C.cat_url '.$this->con->in($params['cat_url']);
			} else {
				$strReq .= 'AND (C.cat_url IS NULL OR C.cat_url NOT '.$this->con->in($params['cat_url']).') ';
			}
		}
		
		if (isset($params['post_status'])) {
			$strReq .= 'AND post_status = '.(integer) $params['post_status'].' ';
		}
		
		if (isset($params['post_selected'])) {
			$strReq .= 'AND post_selected = '.(integer) $params['post_selected'].' ';
		}
		
		if (!empty($params['post_year'])) {
			$strReq .= 'AND '.$this->con->dateFormat('post_dt','%Y').' = '.
			"'".sprintf('%04d',$params['post_year'])."' ";
		}
		
		if (!empty($params['post_month'])) {
			$strReq .= 'AND '.$this->con->dateFormat('post_dt','%m').' = '.
			"'".sprintf('%02d',$params['post_month'])."' ";
		}
		
		if (!empty($params['post_day'])) {
			$strReq .= 'AND '.$this->con->dateFormat('post_dt','%d').' = '.
			"'".sprintf('%02d',$params['post_day'])."' ";
		}
		
		if (!empty($params['post_lang'])) {
			$strReq .= "AND P.post_lang = '".$this->con->escape($params['post_lang'])."' ";
		}
		
		if (!empty($params['search']))
		{
			$words = text::splitWords($params['search']);
			
			if (!empty($words))
			{
				# --BEHAVIOR-- corePostSearch
				if ($this->core->hasBehavior('corePostSearch')) {
					$this->core->callBehavior('corePostSearch',$this->core,array(&$words,&$strReq,&$params));
				}
				
				if ($words)
				{
					foreach ($words as $i => $w) {
						$words[$i] = "post_words LIKE '%".$this->con->escape($w)."%'";
					}
					$strReq .= 'AND '.implode(' AND ',$words).' ';
				}
			}
		}
		/* Gestion des dates de debut et de fin*/
		
		if (!empty($params["date_debut"])){
			$strReq .= 'AND G.date_debut >= "'.$params['date_debut'].'" ';
			
		}
		if (!empty($params["date_fin"])){
			$strReq .= 'AND G.date_fin <= "'.$params['date_fin'].'" ';
			
		}
		if(!empty($params['date_in'])){
			$strReq .= 'AND "'.$params['date_in'].'" BETWEEN G.date_debut AND G.date_fin ';
		}
		if (!empty($params['periode'])){
			$strReq .= 'AND (G.date_debut BETWEEN "'.$params["periode"][0].'" AND "'.$params["periode"][1].'" ';
			$strReq .= 'OR G.date_fin BETWEEN "'.$params["periode"][0].'" AND "'.$params["periode"][1].'" ';
			$strReq .= 'OR "'.$params["periode"][0].'" BETWEEN G.date_debut AND G.date_fin ';
			$strReq .= 'OR "'.$params["periode"][1].'" BETWEEN G.date_debut AND G.date_fin) ';
		}

		/* Fin de la gestion des dates */
		if (!empty($params['sql'])) {
			$strReq .= $params['sql'].' ';
		}
		
		if (!$count_only)
		{
			if (!empty($params['order'])) {
				$strReq .= 'ORDER BY '.$this->con->escape($params['order']).' ';
			} else {
				$strReq .= 'ORDER BY post_dt DESC ';
			}
		}
		
		if (!$count_only && !empty($params['limit'])) {
			$strReq .= $this->con->limit($params['limit']);
		}
		//echo $strReq;	exit();
		$rs = $this->con->select($strReq);
		$rs->core = $this->core;
		$rs->_nb_media = array();
		$rs->extend('rsExtPost');
		
		# --BEHAVIOR-- coreBlogGetPosts
		$this->core->callBehavior('coreBlogGetPosts',$rs);
		
		return $rs;
	}
	
	/**
	 * Met  a jour un evenement
	 *
	 * @param Integer $id
	 * @param curseur $cur Le curseur du post
	 * @param curseur $cur2 Le curseur Agenda
	 */
	public function updPost($id,&$cur, &$cur2= false)
	{
		if (!$this->core->auth->check('usage,contentadmin',$this->id)) {
			throw new Exception(__('You are not allowed to update entries'));
		}
		
		$id = (integer) $id;
		
		if (empty($id)) {
			throw new Exception(__('No such entry ID'));
		}
		
		# Post excerpt and content
		$this->getPostContent($cur,$id);
		
		$this->getPostCursor($cur);
		
		if ($cur->post_url !== null) {
			$cur->post_url = $this->getPostURL($cur->post_url,$cur->post_dt,$cur->post_title,$id);
		}
		
		if (!$this->core->auth->check('publish,contentadmin',$this->id)) {
			$cur->unsetField('post_status');
		}
		
		$cur->post_upddt = date('Y-m-d H:i:s');
		
		#If user is only "usage", we need to check the post's owner
		if (!$this->core->auth->check('contentadmin',$this->id))
		{
			$strReq = 'SELECT post_id '.
					'FROM '.$this->prefix.'post '.
					'WHERE post_id = '.$id.' '.
					"AND user_id = '".$this->con->escape($this->core->auth->userID())."' ";
			
			$rs = $this->con->select($strReq);
			
			if ($rs->isEmpty()) {
				throw new Exception(__('You are not allowed to edit this entry'));
			}
		}
		
		$cur->update('WHERE post_id = '.$id.' ');
		if ($cur)
			$cur2->update('WHERE post_id = '.$id.' ');
		$this->blog->triggerBlog();
	}
	
/**
	Creates a new entry. Takes a cursor as input and returns the new entry
	ID.
	
	@param	cur		<b>cursor</b>		Post cursor
	@param cur2 	<b>cursor</b>		Agenda cursor
	@return	<b>integer</b>		New post ID
	*/
	public function addPost($cur, $cur2)
	{
		if (!$this->core->auth->check('usage,contentadmin',$this->id)) {
			throw new Exception(__('You are not allowed to create an entry'));
		}
		
		# Get ID
		$rs = $this->con->select(
			'SELECT MAX(post_id) '.
			'FROM '.$this->prefix.'post ' 
			);
		
		$cur->post_id = (integer) $rs->f(0) + 1;
		$cur->blog_id = (string) $this->blog->id;
		$cur->post_creadt = date('Y-m-d H:i:s');
		$cur->post_upddt = date('Y-m-d H:i:s');
		$cur->post_tz = $this->core->auth->getInfo('user_tz');
		
		
		# Post excerpt and content
		$this->getPostContent($cur,$cur->post_id);
		
		$this->getPostCursor($cur);
		
		$cur->post_url = $this->blog->getPostURL($cur->post_url,$cur->post_dt,$cur->post_title,$cur->post_id);
		$cur->post_url = 'Agenda/'.$cur->post_url;
		if (!$this->core->auth->check('publish,contentadmin',$this->id)) {
			$cur->post_status = -2;
		}
		
		$cur->insert();
		
		$cur2->post_id = $cur->post_id;;
		$cur2->insert();
		$this->blog->triggerBlog();
		return $cur->post_id;
	}
	
	
	private function getPostContent(&$cur,$post_id)
	{
		$post_excerpt = $cur->post_excerpt;
		$post_excerpt_xhtml = $cur->post_excerpt_xhtml;
		$post_content = $cur->post_content;
		$post_content_xhtml = $cur->post_content_xhtml;
		
		$this->blog->setPostContent(
			$post_id,$cur->post_format,$cur->post_lang,
			$post_excerpt,$post_excerpt_xhtml,
			$post_content,$post_content_xhtml
		);
		
		$cur->post_excerpt = $post_excerpt;
		$cur->post_excerpt_xhtml = $post_excerpt_xhtml;
		$cur->post_content = $post_content;
		$cur->post_content_xhtml = $post_content_xhtml;
	}
	private function getPostCursor(&$cur,$post_id=null)
	{
		if ($cur->post_title == '') {
			throw new Exception(__('No entry title'));
		}
		
		if ($cur->post_content == '') {
			throw new Exception(__('No entry content'));
		}
		
		if ($cur->post_dt == '') {
			$offset = dt::getTimeOffset($this->core->auth->getInfo('user_tz'));
			$now = time() + $offset;
			$cur->post_dt = date('Y-m-d H:i:00',$now);
		}
		
		$post_id = is_int($post_id) ? $post_id : $cur->post_id;
		
		if ($cur->post_content_xhtml == '') {
			throw new Exception(__('No entry content'));
		}
		
		# Words list
		if ($cur->post_title !== null && $cur->post_excerpt_xhtml !== null
		&& $cur->post_content_xhtml !== null)
		{
			$words =
			$cur->post_title.' '.
			$cur->post_excerpt_xhtml.' '.
			$cur->post_content_xhtml;
			
			$cur->post_words = implode(' ',text::splitWords($words));
		}
	}
	
	/**
	Returns a record with post id, title and date for next or previous post
	according to the post ID.
	$dir could be 1 (next post) or -1 (previous post).
	
	@param	post_id				<b>integer</b>		Post ID
	@param	dir					<b>integer</b>		Search direction
	@param	restrict_to_category	<b>boolean</b>		Restrict to post with same category
	@param	restrict_to_lang		<b>boolean</b>		Restrict to post with same lang
	@return	record
	*/
	public function getNextPost($post,$dir,$restrict_to_category=false, $restrict_to_lang=false)
	{
		$dt = $post->post_dt;
		$post_id = (integer) $post->post_id;
		
		if($dir > 0) {
               $sign = '>';
               $order = 'ASC';
          }
          else {
               $sign = '<';
               $order = 'DESC';
          }
		
		$params['post_type'] = $post->post_type;
		$params['limit'] = 1;
		$params['order'] = 'post_dt '.$order.', P.post_id '.$order;
		$params['sql'] =
		'AND ( '.
		"	(post_dt = '".$this->con->escape($dt)."' AND P.post_id ".$sign." ".$post_id.") ".
		"	OR post_dt ".$sign." '".$this->con->escape($dt)."' ".
		') ';
		
		if ($restrict_to_category) {
			$params['sql'] .= $post->cat_id ? 'AND P.cat_id = '.(integer) $post->cat_id : 'AND P.cat_id IS NULL';
		}

		if ($restrict_to_lang) {
			$params['sql'] .= $post->post_lang ? 'AND P.post_lang = \''. $this->con->escape($post->post_lang) .'\'': 'AND P.post_lang IS NULL';
		}
		
		$rs = $this->getPosts($params);
		
		if ($rs->isEmpty()) {
			return null;
		}
		
		return $rs;
	}
}
?>
